using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using UnityEngine;
public class LLMResponseDefine
{
    public class GenerateRequest
    {
        public class RequestModel
        {
            [JsonProperty("model")]
            public string Model { get; set; }

            [JsonProperty("prompt")]
            public string Prompt { get; set; }

            [JsonProperty("suffix")]
            public string Suffix { get; set; }

            [JsonProperty("images")]
            public List<string> Images { get; set; }

            [JsonProperty("format")]
            public string Format { get; set; }

            [JsonProperty("options")]
            public Options Options { get; set; }

            [JsonProperty("system")]
            public string System { get; set; }

            [JsonProperty("template")]
            public string Template { get; set; }

            [JsonProperty("context")]
            public Dictionary<string, object> Context { get; set; }

            [JsonProperty("stream")]
            public bool Stream { get; set; } = false;

            [JsonProperty("raw")]
            public bool Raw { get; set; } = false;

            [JsonProperty("keep_alive")]
            public string KeepAlive { get; set; } = "5m";
        }

        public class Options
        {
            [JsonProperty("temperature")]
            public double Temperature { get; set; }

            [JsonProperty("seed")]
            public int Seed { get; set; }
        }

        private RequestModel request;

        public GenerateRequest(string model, string prompt, bool isJson, bool stream)
        {
            request = new RequestModel()
            {
                Model = model,
                Prompt = prompt,
                Stream = stream,
                Format = isJson ? "json" : ""
            };
        }

        public string ToJson()
        {
            return JsonConvert.SerializeObject(request);
        }
    }

    public class GenerateAck
    {
        public class ResponseModel
        {
            [JsonProperty("model")]
            public string Model { get; set; }

            [JsonProperty("created_at")]
            public DateTime CreatedAt { get; set; } = DateTime.UtcNow;

            [JsonProperty("response")]
            public string Response { get; set; }

            [JsonProperty("done")]
            public bool Done { get; set; }

            [JsonProperty("done_reason")]
            public string DoneReason { get; set; }

            [JsonProperty("context")]
            public List<long> Context { get; set; }

            [JsonProperty("total_duration")]
            public long TotalDuration { get; set; }

            [JsonProperty("load_duration")]
            public long LoadDuration { get; set; }

            [JsonProperty("prompt_eval_count")]
            public int PromptEvalCount { get; set; }

            [JsonProperty("prompt_eval_duration")]
            public long PromptEvalDuration { get; set; }

            [JsonProperty("eval_count")]
            public int EvalCount { get; set; }

            [JsonProperty("eval_duration")]
            public long EvalDuration { get; set; }
        }

        public ResponseModel Response { get; private set; }

        public string Message => Response.Response;
        public string NsConvertToString(long duration)
        {
            double seconds = (double)duration / 1000000000;
            return $"{seconds:F2}s";
        }
        public string Duration => $"total:{NsConvertToString(Response.TotalDuration)} | load:{NsConvertToString(Response.LoadDuration)} | eval:{NsConvertToString(Response.EvalDuration)}";

        public GenerateAck(string input)
        {
            Response = JsonConvert.DeserializeObject<ResponseModel>(input);
        }
    }

    public class ChatRequest
    {
        public class RequestModel
        {
            // 必需字段
            [JsonProperty("model")]
            public string Model { get; set; }

            [JsonProperty("messages")]
            public List<Message> Messages { get; set; }

            // 可选字段
            [JsonProperty("tools")]
            public List<string> Tools { get; set; } // 仅当 stream 为 false 时有效
            [JsonProperty("format")]
            public string Format { get; set; } // "json" 是唯一有效格式
            [JsonProperty("options")]
            public Dictionary<string, object> Options { get; set; } // 例如 temperature, seed 等
            [JsonProperty("stream")]
            public bool Stream { get; set; } // 是否为流式
            [JsonProperty("keep_alive")]
            public string KeepAlive { get; set; } // 默认值：5m

            public RequestModel()
            {
                Messages = new List<Message>();
            }

            // 使用 System.Text.Json 序列化对象为 JSON 字符串
            public string ToJson()
            {
                return JsonConvert.SerializeObject(this);
            }
        }

        public class Message
        {
            [JsonProperty("role")]
            public string Role { get; set; } // "system", "user", "assistant", "tool"

            [JsonProperty("content")]
            public string Content { get; set; }

            [JsonProperty("images")]
            public List<string> Images { get; set; } // 可选字段
            [JsonProperty("tool_calls")]
            public List<string> ToolCalls { get; set; } // 可选字段

            public Message(string role, string content)
            {
                Role = role;
                Content = content;
            }
        }

        public RequestModel Request { get; set; }

        public List<Message> Messages
        {
            get => Request.Messages;
            set
            {
                Request.Messages = value;
            }
        }

        public ChatRequest(string model)
        {
            Request = new RequestModel()
            {
                Model = model
            };
        }

        public void AddMessage(string role, string content)
        {
            Messages.Add(new Message(role, content));
        }

        public string ToJson()
        {
            return Request.ToJson();
        }
    }

    public class ChatAck
    {
        public class ChatResponse
        {
            [JsonProperty("model")]
            public string Model { get; set; }

            [JsonProperty("created_at")]
            public DateTime CreatedAt { get; set; }

            [JsonProperty("message")]
            public ChatMessage Message { get; set; }

            [JsonProperty("done_reason")]
            public string DoneReason { get; set; }

            [JsonProperty("done")]
            public bool Done { get; set; }

            [JsonProperty("total_duration")]
            public long TotalDuration { get; set; }

            [JsonProperty("load_duration")]
            public long LoadDuration { get; set; }

            [JsonProperty("prompt_eval_count")]
            public int PromptEvalCount { get; set; }

            [JsonProperty("prompt_eval_duration")]
            public long PromptEvalDuration { get; set; }

            [JsonProperty("eval_count")]
            public int EvalCount { get; set; }

            [JsonProperty("eval_duration")]
            public long EvalDuration { get; set; }
        }

        public class ChatMessage
        {
            [JsonProperty("role")]
            public string Role { get; set; }

            [JsonProperty("content")]
            public string Content { get; set; }
        }

        public ChatResponse response;
        public string Message => response.Message.Content;
        public ChatAck(string input)
        {
            response = JsonConvert.DeserializeObject<ChatResponse>(input);
        }
    }

    public class LocalHistory : IDisposable
    {
        public int id;
        public string startTime;
        public string model;
        public ChatRequest LocalRequest { get; set; }

        public LocalHistory(string model, string localHistoryJson)
        {

        }
        public LocalHistory(string model)
        {
            id = 1001;
            this.model = model;
            startTime = TimeUtility.GetCurrentTime();
            LocalRequest = new ChatRequest(model);
        }

        public void AddUserMessage(string content)
        {
            LocalRequest.AddMessage("user", content);
        }
        public void AddassistantMessage(string contnet)
        {
            LocalRequest.AddMessage("assistant", contnet);
        }

        public string ToJson()
        {
            return LocalRequest.ToJson();
        }
        public void Dispose()
        {
            LocalRequest = null;
            Console.WriteLine($"release at: {TimeUtility.GetCurrentTime()}");
        }

    }

    public static class TimeUtility
    {
        // 获取当前时间，格式为："created_at": "2024-11-28T05:08:20.434036Z"
        public static string GetCurrentTime()
        {
            // 获取当前的 UTC 时间
            DateTime utcNow = DateTime.UtcNow;

            // 使用自定义格式将时间转化为指定格式
            string formattedTime = utcNow.ToString("yyyy-MM-ddTHH:mm:ss.ffffffZ");

            return formattedTime;
        }
    }

}
